package 栈;

import java.util.LinkedList;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
 */
public class _150_逆波兰表达式求值 {
    public static void main(String[] args) {
        System.out.println(evalRPN(new String[]{"2", "1", "+", "3", "*"}));
        System.out.println(evalRPN(new String[]{"4","13","5","/","+"}));
    }
    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for (String token : tokens) {
            int pop1;
            int pop2;
            switch (token) {
                case "+":
                    pop1 = stack.pop();
                    pop2 = stack.pop();
                    stack.push(add(pop2,pop1));
                    break;
                case "-":
                    pop1 = stack.pop();
                    pop2 = stack.pop();
                    stack.push(mul(pop2,pop1));
                    break;
                case "*":
                    pop1 = stack.pop();
                    pop2 = stack.pop();
                    stack.push(times(pop2,pop1));
                    break;
                case "/":
                    pop1 = stack.pop();
                    pop2 = stack.pop();
                    stack.push(div(pop2,pop1));
                    break;
                default:
                    stack.push(Integer.parseInt(token));
                    break;
            }
        }

        return stack.pop();
    }

    private static int add(int a, int b) {
        return (a + b);
    }

    private static int div(int a, int b) {
        return a / b;
    }

    private static int mul(int a, int b) {
        return a - b;
    }

    private static int times(int a, int b) {
        return a * b;
    }
}
